package com.ocean.clearance.conf;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class RabbitConfig { // 延迟队列的话可以通过后台管理界面手动追加x-message-ttl,x-dead-letter-exchange和x-dead-letter-routing-key来做

	@Value("${spring.rabbitmq.host}")
	private String host;
	
	@Value("${spring.rabbitmq.port}")
	private int port;

	@Value("${spring.rabbitmq.username}")
	private String username;

	@Value("${spring.rabbitmq.password}")
	private String password;

	@Value("${spring.rabbitmq.virtual-host}")
	private String virtual_host;

	@Bean
	public ConnectionFactory connectionFactory() {
		CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host, port);
		connectionFactory.setUsername(username);
		connectionFactory.setPassword(password);
		connectionFactory.setVirtualHost(virtual_host);
		connectionFactory.setChannelCacheSize(100);
		connectionFactory.setPublisherConfirms(true);
		return connectionFactory;
	}

	@Bean
	@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
	// 必须是prototype类型
	public RabbitTemplate rabbitTemplate() {
		RabbitTemplate template = new RabbitTemplate(connectionFactory());
		template.setConfirmCallback(msgSendConfirmCallBack());
		template.setReturnCallback(msgSendReturnCallback());
		return template;
	}

	@Bean
	public MsgSendConfirmCallBack msgSendConfirmCallBack() {
		return new MsgSendConfirmCallBack();
	}

	@Bean
	public MsgSendReturnCallback msgSendReturnCallback() {
		return new MsgSendReturnCallback();
	}

}
